package com.goldcn.user.service;

import com.goldcn.common.consts.RestConst;
import com.goldcn.common.exception.ServiceException;
import com.goldcn.common.util.IdGen;
import com.goldcn.enums.RoleCodeEnum;
import com.goldcn.enums.TopDeptEnum;
import com.goldcn.interceptor.SystemContext;
import com.goldcn.user.dao.OrganizationalMapper;
import com.goldcn.user.dao.UserInfoMapper;
import com.goldcn.user.dao.UserRoleMapper;
import com.goldcn.user.dao.UserTransferMapper;
import com.goldcn.user.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 *
 */
@Service
@Transactional
public class UserTransferService {

    @Autowired
    UserTransferMapper userTransferMapper;
    @Autowired
    UserInfoMapper userInfoMapper;
    @Autowired
    OrganizationalMapper organizationalMapper;
    @Autowired
    UserRoleMapper userRoleMapper;
    @Autowired
    OrganizationalService organizationalService;

    public int insertSelective(UserApply record){
        //更新员工状态
        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(record.getUserId());
        if(record.getDeptID() == null || organizationalMapper.selectByPrimaryKey(record.getDeptID()) == null){
            throw new ServiceException("未获取到调度部门，调度失败", RestConst.ErrorCode.FORM_FAIL);
        }
        if(Objects.equals(userInfo.getOrganizationalID(),record.getDeptID())){
            throw new ServiceException("用户已经在该部门，调度失败", RestConst.ErrorCode.FORM_FAIL);
        }
        if(userTransferMapper.selectBySimpleUserID(userInfo.getUserID()) != null){
            throw new ServiceException("上次调动申请未审核通过，请不要重复申请", RestConst.ErrorCode.FORM_FAIL);
        }
        //插入申请记录
        UserTransfer userTransfer = new UserTransfer();
        userTransfer.setId(IdGen.get().nextId());
        userTransfer.setUserId(userInfo.getUserID());
        userTransfer.setOrganizationalID(record.getDeptID());
        userTransfer.setState(2);
        userTransfer.setApplyTime(System.currentTimeMillis());
        userTransferMapper.insertSelective(userTransfer);
        //更新用户信息
        userInfo.setLastOrganizationalID(record.getDeptID());//临时存储
        userInfo.setIsStop(0);
        userInfo.setState(2);
        //userInfo.setLastTransferTime(userTransfer.getApplyTime());
        userInfo.setLastApplyTime(userTransfer.getApplyTime());
        userInfo.setUpdateTime(System.currentTimeMillis());
        return userInfoMapper.updateByPrimaryKeySelective(userInfo);
    }

    public String getOrganizational(Long organizationalID){
        Organizational oz = organizationalMapper.selectByPrimaryKey(organizationalID);

        TopDeptEnum topDeptEnum = TopDeptEnum.valuekOf(oz.getCompanyID());
        String topDeptName = topDeptEnum != null ? topDeptEnum.getDeptName() : "总部";
        if (oz == null) {
            return "";
        } else {
            switch (oz.getLevel()) {
                case 1:
                    return topDeptName;
                case 2:
                    return topDeptName+"/" + oz.getOrganizationalName();
                case 3:
                    Organizational ozt = organizationalMapper.selectByPrimaryKey(oz.getBranchID());
                    return topDeptName+"/" + ozt.getOrganizationalName() + "/" + oz.getOrganizationalName();
                case 4:
                    Organizational oztb = organizationalMapper.selectByPrimaryKey(oz.getBranchID());
                    Organizational oztt = organizationalMapper.selectByPrimaryKey(oz.getTwoLevelBranchID());
                    return topDeptName+"/" + oztb.getOrganizationalName() + "/" + oztt.getOrganizationalName() + "/" + oz.getOrganizationalName();
            }
        }
        return "";
    }

    public List<UserInfo> selectEmployee(String keyword){
        return userInfoMapper.selectEmployee(keyword,SystemContext.getCompanyID());
    }

    public void parseEmployee(Long userID){
        userRoleMapper.deleteByUserID(userID);

        UserRole userRole = new UserRole();
        userRole.setRoleID(organizationalService.getRole(SystemContext.getCompanyID(), RoleCodeEnum.EMPLOYEE.getCode()).getRoleID());
        userRole.setID(IdGen.get().nextId());
        userRole.setUserID(userID);
        userRoleMapper.insert(userRole);
    }

    /**
     * 员工升级成管理员
     * 部门自动调度到新部门
     */
    public void parseAdmin(){

    }

    /**
     * 员工升级为管理员（applyTime、checkTime无）
     * @param ui
     * @param organizational
     */
    private void saveUserTransferRecord(UserInfo ui,Organizational organizational){
        UserTransfer userTransfer = new UserTransfer();
        userTransfer.setId(IdGen.get().nextId());
        userTransfer.setUserId(ui.getUserID());
        userTransfer.setOrganizationalID(organizational.getoID());
        userTransfer.setOnTime(ui.getLastTransferTime());
        userTransfer.setState(0);
        userTransferMapper.insertSelective(userTransfer);
    }

    /**
     * 员工调度审核
     * @param ui
     * @param organizational
     * @param pass
     */
    public void saveUserTransferRecord(UserInfo ui,Organizational organizational,boolean pass){
        UserTransfer userTransfer = new UserTransfer();
        userTransfer.setId(IdGen.get().nextId());
        userTransfer.setUserId(ui.getUserID());
        userTransfer.setOrganizationalID(organizational == null ? ui.getOrganizationalID():organizational.getoID());
        userTransfer.setOnTime(System.currentTimeMillis());
        userTransfer.setState(pass ? 0 : 1);
        userTransfer.setCheckTime(System.currentTimeMillis());
        userTransferMapper.insertSelective(userTransfer);
    }

    public void checkUserTransferRecord(UserInfo ui,boolean pass){
        UserTransfer userTransfer = userTransferMapper.selectByUserID(ui.getUserID(),
                pass ? ui.getOrganizationalID():ui.getLastOrganizationalID());
        userTransfer.setOnTime(pass ? ui.getLastTransferTime() : null);
        userTransfer.setState(pass ? 0 : 1);
        userTransfer.setCheckTime(System.currentTimeMillis());
        userTransferMapper.updateByPrimaryKey(userTransfer);
    }

    /**
     *
     * @param userInfo
     * @param organizational
     * @param type 1员工升级为管理员
     */
    public void saveUserTransferRecord(UserInfo userInfo,Organizational organizational,Integer type){
        if(type == 1){
            saveUserTransferRecord(userInfo,organizational);
        }
    }



}
